<?php

namespace App\ApiFrontend;

use App\Domains\UserDomain;
use App\Http\Controllers\ApiBaseController;
use App\Models\UserModel;
use Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 *  登陆
 */
class Register extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
    // 定义规则
    $ruleArr = [
      'username'=>'required|unique:user,username',
      'company'=>'required',
      'password'=>'required',
      'name'=>'required',
      'phone'=>'required',
      'email'=>'required',
      'nickname'=>'required',
    ];
    $messageArr = [
      'required' => ':attribute必须填写',
      'min' => ':attribute必须填写',
      'unique' => ':attribute已经被注册',
    ];
    //验证
    $validator = Validator::make(request()->all(), $ruleArr, $messageArr, [
      'username'=>"用户名"
    ]);
    //验证失败
    if ($validator->stopOnFirstFailure()->fails()) {
      $this->result["code"] = 1;
      $this->result["message"] = $validator->errors()->first();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $username = \request('username');
    $password = \request('password');
    try {
      //1.user
      $userId = DB::table('user')->insertGetId([
        'username'=>$username,
        'password'=> \Illuminate\Support\Facades\Hash::make($password),
        'phone'=>request('phone'),
        'status'=>1,
        'createTime'=>date("Y-m-d H:i:s"),
        'loginTime'=>date("Y-m-d H:i:s"),
        'groupId'=>1,
      ]);
      //2.member
      DB::table('member')->insert([
        'userId'=>$userId,
        'name'=>request('name'),
        'username'=>$username,
        'company'=>request('company'),
        'email'=>request('email'),
        'tel'=>request('phone'),
        'nickname'=>request('nickname'),
      ]);
      //3. 自动登录
      $user = UserModel::find($userId);
      $this->result["message"] = '注册成功';
      $this->result['data'] = [
        'token' => $user->getAuthToken(),
        'username' => $user->username,
        'groupName' => \DB::table('member_group')->where('id',1 )->value('name'),
      ];

    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
    return;
  }
}
